<template>
  <div id="register">
    <!-- 导航栏 -->
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="onClickReturn"
      fixed
      z-index="3"
    />
    <!-- 头部信息 -->
    <span class="msg">重置密码</span>
    <!-- 申请表单 -->
    <van-form @submit="onSubmit" id="registerForm">
      <!-- 基础信息 -->
      <van-tag mark type="primary" size="medium" class="tag">基础信息</van-tag>
      <van-cell-group inset>
        <van-field
          v-model="basic_info.username"
          name="username"
          label="用户名"
          label-width="1.9rem"
          placeholder="请输入用户名"
          left-icon="user-o"
          :rules="[{ validator:usernameValidator, message: '请填写用户名' }]"
        />
        <!-- 密码 -->
        <van-field
          v-model="basic_info.password"
          type="password"
          name="password"
          label="密码"
          label-width="1.9rem"
          placeholder="请输入密码"
          left-icon="question-o"
          :rules="[{ validator: passwordValadator,required: true, message: '请填写密码' }]"
        />
        <!-- 确认密码 -->
        <van-field
          v-model="confirmPwd"
          type="password"
          name="password"
          label="确认密码"
          label-width="1.9rem"
          placeholder="请再次输入密码"
          left-icon="passed"
          :rules="[
            {
              validator: validatorPwd,
              require: true,
              message: '请再次填写密码',
            },
          ]"
        />
        <!-- 短信验证码 -->
        <van-field
          v-model="verfiedCode"
          name="verfiedCode"
          center
          clearable
          label="短信验证码"
          label-width="1.9rem"
          left-icon="comment-o"
          placeholder="请输入验证码"
          :rules="[
            { required: true, message: '请输入验证码', trigger: 'onBlur' },
          ]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="!basic_info.phone || verfied.isSend || !canSend"
              @click="sendVerfyCode"
              >{{verfied.vbtnMessage }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          重置
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Button,
  Icon,
  CellGroup,
  Toast,
  Tag,
  Image,
  RadioGroup,
  Radio,
  Cell,
  Uploader,
  NavBar,
} from "vant";
import { sendVerfiedCode,reg_tel,VerfyingCode} from "@/utils/verifyCode.js";
import {changePassword,isRegisted} from "@/api/UserBaseAPI/register.js"
import {cancelPromise} from "@/utils/cancelPromise.js"
export default {
  name: "register",
  data() {
    return {
      //基础信息
      basic_info: {
        username: "",
        password: "",
        phone:""
      },
      //验证码
      verfiedCode: "",
      //确认密码
      confirmPwd: "",
      //发送验证码
       verfied:{
        isSend: false,
        vbtnMessage: "发送验证码",
        vtime: 0,
      },
      //是否能发送验证码
      canSend:false
    };
  },
  methods: {
    //发送验证码
    sendVerfyCode() {
      this.verfied.phone = String(this.basic_info.phone)
      //console.log(this.verfied.phone);
      sendVerfiedCode.call(this.verfied);
    },
    //导航栏返回
    onClickReturn() {
      history.back();
    },
    //确认密码校验
    validatorPwd() {
      if (!this.confirmPwd) return "请再次填写密码";
      return this.confirmPwd != this.basic_info.password
        ? "输入的两次密码不一致"
        : true;
    }, 
    //密码校验
    passwordValadator(){
      if(this.basic_info.password.indexOf(" ")!=-1) return "密码不能存在空格"
      let pwd = String(this.basic_info.password)
      if(pwd.length< 6 || pwd.length >18){
        return "密码长度需在6到18位之间"
      }
    },
    //用户名校验
    usernameValidator(){
       let username = this.basic_info.username;
       this.canSend = false
       if(!username) return "请填写用户名";
       return cancelPromise.request("username",isRegisted({type:'username',verfieditem:username}).then(res=>{
         if(!res.isRegisted){
           return "该用户名未被注册"
         }
         else{
             this.basic_info.phone = res.phone
             this.canSend = true
         }
      })
      .catch(err =>{
         Toast.fail({
           duration:1000,
           orbidClick: true,
           message:err
         })
      }))
    },
    //修改密码
    onSubmit(values){
      let params = {...this.basic_info};
      //params.phone = String(params.phone)
      const toast1 = Toast.loading({
          duration:0,
          forbidClick: true,
          message: "重置密码中...",
          onOpened: async() =>{
            //console.log(this.verfiedCode);
            let res = await VerfyingCode(String(params.phone),this.verfiedCode)
            //console.log(res);
            if(res.success){
                res = await changePassword(params)
                if(res.success){
                  toast1.clear();
                  Toast.success({
                    duration:1500,
                    forbidClick:true,
                    message:"修改成功!",
                    onClose:()=>{
                       history.back();
                    }
                  })
                }                          
            }
            else{
                  toast1.clear();
                  Toast.fail({
                    duration:1500,
                    forbidClick:true,
                    message:res.message,
                  })
            }  
          }
      })
    }
  },
  components: {
    [Form.name]: Form,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Image.name]: Image,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Cell.name]: Cell,
    [Uploader.name]: Uploader,
    [NavBar.name]: NavBar,
  },
  computed:{
    reg_phone(){
      return reg_tel.test(this.basic_info.phone)
    }
  },
};
</script>
<style lang="less" scoped>
@import "../../assets/css/gradient.css";
#register {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f7f8fa;
}
#registerForm {
  position: absolute;
  width: 100%;
  top: 145px;
  left: 50%;
  transform: translate(-50%, 0);
  overflow: hidden;
}
//分类标签
.tag {
  margin: 10px;
  transform: translate(-135px, 0);
}
//头部提示信息
.msg {
  position: absolute;
  top: 65px;
  left: 20px;
  font-size: 26px;
  font-weight: bolder;
  text-align: left;
  letter-spacing: 2px;
}
.msg::after {
  content: "欢迎加入校园社区~";
  display: block;
  font-size: 16px;
  font-weight: normal;
  color: #6d6c6c;
  letter-spacing: 0px;
}
</style>